package com.project.rbac.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.rbac.entity.SysDept;
import com.project.rbac.exception.ParamException;
import com.project.rbac.mapper.SysDeptMapper;
import com.project.rbac.service.ISysDeptService;
import com.project.rbac.util.BeanValidator;
import com.project.rbac.util.LevelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * <p>
 * 部门表 服务实现类
 * </p>
 *
 * @author nickBoy
 * @since 2021-06-15
 */
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements ISysDeptService {

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Override
    public Integer insert(SysDept dept) {
        BeanValidator.check(dept);
        if (checkExist(dept.getParentId(), dept.getName(), dept.getId())) {
            throw new ParamException("同一层级下存在相同名称的部门");
        }
        dept.setLevel(LevelUtil.calculateLevel(getLevel(dept.getParentId()), dept.getParentId()));
        dept.setOperator("system");
        dept.setOperateIp("127.0.0.1");
        dept.setOperateTime(LocalDateTime.now());
        return sysDeptMapper.insert(dept);
    }

    private boolean checkExist(Integer parentId, String deptName, Integer deptId) {
        return sysDeptMapper.countByNameAndParentId(parentId, deptName, deptId) > 0;
    }
    private String getLevel(Integer parentId) {
        SysDept sysDept = this.baseMapper.selectById(parentId);
        if (Objects.nonNull(sysDept)) {
            return sysDept.getLevel();
        }
        return null;
    }
}
